import { routeList } from '@/router/index.jsx';
import StringUtil from '@/utils/string.js';
import { SuspenseLoading } from '@/components/index.jsx';

// 路由增加懒加载组件
export function replaceLazyRoute(list) {
  list.forEach((item) => {
    if (item.element && item.isLazy !== false) {
      item.element = <SuspenseLoading>{item.element}</SuspenseLoading>;
    }
    if (item.children) {
      replaceLazyRoute(item.children);
    }
  });
}

// 路由列表
export function getRoutes(routeList) {
  replaceLazyRoute(routeList);
  return routeList;
}

// 根据绝对路径获取路由
export function findRouteByAbsolutePath(absolutePath) {
  function find(findAbsolutePath, routes, parentPath = '') {
    for (let i = 0; i < routes.length; i++) {
      const route = routes[i];
      const paths = generateRoutePatterns(route.path);
      const pPath = StringUtil.isNotEmpty(parentPath) ? `${parentPath}/` : ``;
      if (paths.length > 1) {
        // 可选路由段，一定没有子路由
        for (let j = 0; j < paths.length; j++) {
          const path = paths[j];
          const absolutePath = pPath + path;
          if (matchRoute(absolutePath, findAbsolutePath)) {
            return route;
          }
        }
      } else {
        // 路由是绝对路径
        const absolutePath = pPath + route.path;
        if (route?.path != null) {
          if (absolutePath === findAbsolutePath) {
            return route;
          }
        }
        // 递归查找子路由
        if (Array.isArray(route?.children) && route.children.length > 0) {
          const targetRoute = find(findAbsolutePath, route.children, absolutePath);
          if (targetRoute) {
            return targetRoute;
          }
        }
      }
    }
  }

  return find(absolutePath, routeList);
}

// 生成路由规则匹配路径列表
export function generateRoutePatterns(path) {
  const patterns = [];
  const segments = path.split('?');
  let start = '';
  for (const segment of segments) {
    patterns.push(start + segment);
    start = segment;
  }
  return patterns;
}

// 匹配路由规则的函数
export function matchRoute(rule, path) {
  const patterns = generateRoutePatterns(rule);
  for (let pattern of patterns) {
    // 如果直接匹配到路由规则，则返回路由规则
    if (pattern === path) {
      return rule;
    } else {
      const regex = new RegExp(
        '^' +
          pattern.replace(/:[a-zA-Z0-9_\u4e00-\u9fa5-]+/g, '([a-zA-Z0-9_\u4e00-\u9fa5-]+)') +
          '(?!/)$'
      );
      const match = path.match(regex);
      if (match) {
        return rule;
      }
    }
  }
  return null;
}
